<template>
    <div class="orders-view">
        <h2>订单管理</h2>
        <div class="search-bar">
            <input v-model="searchUserId" type="text" placeholder="输入用户ID查询订单" @keyup.enter="searchOrdersByUserId">
            <button @click="searchOrdersByUserId">查询</button>
        </div>

        <div v-if="loading" class="loading-state">
            <div class="spinner"></div>
            <p>正在加载订单...</p>
        </div>

        <div v-else-if="error" class="error-state">
            <p>⚠️ {{ error }}</p>
            <button @click="searchOrdersByUserId" class="retry-btn">重试</button>
        </div>

        <div v-else class="order-list">
            <div v-for="order in orders" :key="order.orderid" class="order-item">
                <div class="order-header">
                    <span class="order-id">#{{ order.orderid }}</span>
                    <span class="order-status" :class="statusClass(order.status)">
                        {{ order.status }}
                    </span>
                </div>
                <div class="order-details">
                    <p><strong>客户ID：</strong>{{ order.userid }}</p>
                    <p><strong>下单时间：</strong>{{ formatDate(order.createtime) }}</p>
                    <p><strong>总金额：</strong>¥{{ order.totalprice?.toFixed(2) }}</p>
                </div>
                <div class="order-actions">
                    <router-link :to="{
                        name: 'orderDetail',  // 必须与路由配置中的名称一致
                        params: { orderid: order.orderid, userid: order.userid }
                    }" class="view-btn">
                        查看详情
                    </router-link>
                </div>
            </div>
            <div v-if="orders.length === 0" class="empty-state">
                <p>暂无订单数据</p>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter, onBeforeRouteLeave } from 'vue-router'
import { getOrderByUserid } from '../../api/order.js'

const router = useRouter()
const route = useRoute()

// 响应式数据
const orders = ref([])
const loading = ref(false)
const error = ref(null)
const searchUserId = ref('')

// 路由离开时保存状态
onBeforeRouteLeave((to, from) => {
    if (to.name === 'orderDetail') {
        from.meta.savedState = {
            searchUserId: searchUserId.value,
            orders: orders.value,
            loading: loading.value,
            error: error.value
        }
    }
})

// 组件挂载时恢复状态
onMounted(() => {
    if (route.meta.savedState) {
        searchUserId.value = route.meta.savedState.searchUserId
        orders.value = route.meta.savedState.orders
        loading.value = route.meta.savedState.loading
        error.value = route.meta.savedState.error
        route.meta.savedState = null
    }
})

// 状态样式
const statusClass = (status) => {
    const statusMap = {
        '已支付': 'paid',
        '未支付': 'unpaid',
        '已取消': 'canceled'
    }
    return statusMap[status] || ''
}

// 日期格式化
const formatDate = (timestamp) => {
    if (!timestamp) return '-'
    return new Date(timestamp).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    })
}

// 查询订单
const searchOrdersByUserId = async () => {
    if (!searchUserId.value.trim()) {
        error.value = '请输入有效的用户ID'
        return
    }

    try {
        loading.value = true
        error.value = null
        const response = await getOrderByUserid(searchUserId.value)

        if (response.data?.code === 1) {
            orders.value = response.data.data || []
            if (orders.value.length === 0) {
                error.value = '未找到相关订单'
            }
        } else {
            throw new Error(response.data?.msg || '获取订单失败')
        }
    } catch (err) {
        console.error('订单加载失败:', err)
        error.value = err.message || '请求失败，请检查网络连接'
        orders.value = []
    } finally {
        loading.value = false
    }
}
</script>

<style scoped>
.orders-view {
    padding: 1rem;
    max-width: 1200px;
    margin: 0 auto;
}

.search-bar {
    margin: 1.5rem 0;
    display: flex;
    gap: 0.5rem;
}

.search-bar input {
    flex: 1;
    padding: 0.8rem;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 1rem;
}

.search-bar button {
    padding: 0.8rem 1.5rem;
    background: #007bff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background 0.2s;
}

.search-bar button:hover {
    background: #0056b3;
}

.order-list {
    display: grid;
    gap: 1rem;
}

.order-item {
    background: white;
    border-radius: 8px;
    padding: 1.5rem;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
}

.order-id {
    color: #666;
    font-size: 0.9rem;
}

.order-status {
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.85rem;
}

.order-status.paid {
    background: #e8f5e9;
    color: #2e7d32;
}

.order-status.unpaid {
    background: #ffebee;
    color: #c62828;
}

.order-status.canceled {
    background: #fff3e0;
    color: #ef6c00;
}

.order-details p {
    margin: 0.5rem 0;
    color: #444;
}

.order-actions {
    margin-top: 1rem;
    display: flex;
    gap: 0.5rem;
}

.view-btn {
    display: inline-block;
    padding: 8px 16px;
    background: #007bff;
    color: white;
    border-radius: 4px;
    text-decoration: none;
    transition: background 0.2s;
}

.view-btn:hover {
    background: #0056b3;
}

.loading-state {
    text-align: center;
    padding: 2rem;
}

.spinner {
    width: 40px;
    height: 40px;
    margin: 0 auto 1rem;
    border: 3px solid #ddd;
    border-top-color: #007bff;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    to {
        transform: rotate(360deg);
    }
}

.error-state {
    text-align: center;
    padding: 2rem;
    color: #dc3545;
}

.retry-btn {
    margin-top: 1rem;
    padding: 8px 16px;
    background: #007bff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.empty-state {
    text-align: center;
    padding: 2rem;
    color: #666;
}
</style>